using Microsoft.AspNetCore.Mvc;
using B.S.DataBase.MyProject.Domain.PatientMobileDevice;
using B.S.DataBase.MyProject.Infrastructure;
using System.Security.Claims;

namespace MedicalPCTerminal.Write.API.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class DoctorController : ControllerBase
    {
        private readonly SqlSugarContext _sugar;

        public DoctorController(SqlSugarContext sugar)
        {
            _sugar = sugar;
        }

        [HttpGet("GetChatListItem")]
        public async Task<IActionResult> GetChatListItem(string UserName, int Role)
        {
            try
            {
                var chatList = await _sugar.db.Queryable<ChatListItem>()
                    .Where(x => !x.IsDel && x.Sender == UserName)
                    .OrderByDescending(x => x.ChatTime)
                    .ToListAsync();

                return Ok(new { code = 200, data = chatList });
            }
            catch (Exception ex)
            {
                return BadRequest(new { code = 400, message = ex.Message });
            }
        }

        [HttpGet("GetChatHistory")]
        public async Task<IActionResult> GetChatHistory(string UserId, string ContactId, int Limit = 50)
        {
            try
            {
                var messages = await _sugar.db.Queryable<ChatListItem>()
                    .Where(x => !x.IsDel &&
                               ((x.Sender == UserId && x.ContactName == ContactId) || 
                                (x.Sender == ContactId && x.ContactName == UserId)))
                    .OrderByDescending(x => x.ChatTime)
                    .Take(Limit)
                    .ToListAsync();

                return Ok(new { code = 200, data = messages });
            }
            catch (Exception ex)
            {
                return BadRequest(new { code = 400, message = ex.Message });
            }
        }

        [HttpPost("MarkMessagesAsRead")]
        public async Task<IActionResult> MarkMessagesAsRead([FromBody] string[] messageIds)
        {
            try
            {
                await _sugar.db.Updateable<ChatListItem>()
                    .SetColumns(x => new ChatListItem { HasRedDot = false })
                    .Where(x => messageIds.Contains(x.ChatListItemID.ToString()))
                    .ExecuteCommandAsync();

                return Ok(new { code = 200, message = "标记已读成功" });
            }
            catch (Exception ex)
            {
                return BadRequest(new { code = 400, message = ex.Message });
            }
        }
    }
} 